package edu.gyc.producer.consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//简化版生产者消费者问题，生产一个，消费一个
public class SynchronizeTest {
    public static void main(String[] args) {

        MyStock myStock=new MyStock();
        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                myStock.add();
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                myStock.get();
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                myStock.add();
            }
        },"CC").start();

        new Thread(()->{
            for (int i = 1; i <=5; i++) {
                myStock.get();
            }
        },"DD").start();
    }
}
class MyStock{
    private int number=0;
    public synchronized void add(){


            while (number != 0) { //不能用if判断，用if,可以测试2个生产，2个消费

                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            number++;
            System.out.println(Thread.currentThread().getName()+"\t "+number);

            notifyAll();


    }

    public synchronized void get(){

            while (number == 0) {

                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            number--;
            System.out.println(Thread.currentThread().getName()+"\t "+number);

           notifyAll();


    }
}



